package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息：{}", setmealDto);
        boolean saveSetmealFlag = setmealService.save(setmealDto);
        if (!saveSetmealFlag) {
            return R.error("套餐保存失败");
        }
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
            boolean saveSetmealDishFlag = setmealDishService.save(setmealDish);
            if (!saveSetmealDishFlag) {
                return R.error("套餐内菜品保存失败");
            }
        }
        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public /*R<Page>*/ R<HashMap<String, Object>> page(Integer page, Integer pageSize, String name) {
        //分页构造器对象
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        // Page<SetmealDto> setmealDtoPage = new Page<>();
        HashMap<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<Setmeal> setmealLQW = new LambdaQueryWrapper<>();
        // 根据name 模糊查询
        setmealLQW.like(name != null, Setmeal::getName, name);
        setmealService.page(setmealPage, setmealLQW);
        //对象拷贝 除了 "records"
        // BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        map.put("total", setmealPage.getTotal());
        List<Setmeal> setmeals = setmealPage.getRecords();
        ArrayList<SetmealDto> setmealDtos = new ArrayList<>();
        for (Setmeal record : setmeals) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(record, setmealDto);
            Long categoryId = record.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //得到分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            setmealDtos.add(setmealDto);
        }
        map.put("records", setmealDtos);
        // setmealDtoPage.setRecords(setmealDtos);
        return R.success(map);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        LambdaQueryWrapper<Setmeal> setmealLQW = new LambdaQueryWrapper<>();
        setmealLQW.in(Setmeal::getId, ids);
        setmealLQW.eq(Setmeal::getStatus, 1);
        int setmealCount = setmealService.count(setmealLQW);
        if (setmealCount >= 1) {
            return R.error("售卖中的套餐不能删除");
        }
        boolean removeSetmealByIdsFlag = setmealService.removeByIds(ids);
        if (!removeSetmealByIdsFlag) {
            return R.error("删除失败");
        }
        LambdaQueryWrapper<SetmealDish> setmealDishLQW = new LambdaQueryWrapper<>();
        setmealDishLQW.in(SetmealDish::getSetmealId, ids);
        //删除套餐菜品关系表中的数据
        boolean removeSetmealDishesFlag = setmealDishService.remove(setmealDishLQW);
        if (!removeSetmealDishesFlag) {
            return R.error("删除套餐中相应的菜品失败");
        }
        return R.success("删除成功");
    }

    /**
     * 切换套餐状态
     * LambdaUpdateWrapper.set
     *
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> changeStatus(@RequestParam List<Long> ids, @PathVariable Integer status) {
        log.info("ids:{}", ids);
        if (ids == null || ids.size() == 0) {
            return R.error("请求参数有误");
        }
        LambdaUpdateWrapper<Setmeal> SetmealLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        SetmealLambdaUpdateWrapper.set(Setmeal::getStatus, status);
        SetmealLambdaUpdateWrapper.in(Setmeal::getId, ids);
        boolean changeStatusFlag = setmealService.update(SetmealLambdaUpdateWrapper);
        if (!changeStatusFlag) {
            return R.error("套餐状态修改失败");
        }
        return R.success("套餐状态修改成功");
    }

    /**
     * 根据 id 回显套餐
     */
    @GetMapping("/{id}")
    public R<SetmealDto> showSetmeal(@PathVariable Long id) {
        log.info("id:{}", id);
        if (id == null || id <= 0) {
            return R.error("请求参数有误");
        }
        Setmeal setmealById = setmealService.getById(id);
        if (setmealById == null) {
            return R.error("查询不到该套餐");
        }
        LambdaQueryWrapper<SetmealDish> setmealDishLQW = new LambdaQueryWrapper<>();
        setmealDishLQW.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLQW);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmealById, setmealDto, "setmealDishes");
        setmealDto.setSetmealDishes(setmealDishList);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> updateSetmeal(@RequestBody SetmealDto setmealDto) {
        log.info("setmealDto:{}", setmealDto);
        if (setmealDto == null) {
            return R.error("请求参数有误");
        }
        setmealService.updateById(setmealDto);
        // 删除 原本套餐中的菜品
        LambdaQueryWrapper<SetmealDish> setmealDishLQW = new LambdaQueryWrapper<>();
        setmealDishLQW.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(setmealDishLQW);
        // 新增 setmealDishes
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        // 为每个 setmealDish 设置 Id
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        boolean saveSetmealDishFlag = setmealDishService.saveBatch(setmealDishes);
        if (!saveSetmealDishFlag) {
            return R.error("向套餐中新增菜品失败");
        }
        return R.success("成功修改套餐");
    }

    @GetMapping("/list")
    public R<List<Setmeal>> listByCategoryId(Setmeal setmeal) {
        log.info("setmeal:{}", setmeal);
        LambdaQueryWrapper<Setmeal> setmealLQW = new LambdaQueryWrapper<>();
        setmealLQW.eq(null != setmeal.getCategoryId(), Setmeal::getCategoryId, setmeal.getCategoryId());
        setmealLQW.eq(null != setmeal.getStatus(), Setmeal::getStatus, setmeal.getStatus());
        List<Setmeal> list = setmealService.list(setmealLQW);
        return R.success(list);
    }

    @GetMapping("/dish/{id}")
    public R<List<SetmealDish>> dishesBySetmealId(@PathVariable Long id) {
        log.info("id:{}", id);
        LambdaQueryWrapper<SetmealDish> setmealDishLQW = new LambdaQueryWrapper<>();
        setmealDishLQW.eq(null != id, SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLQW);
        return R.success(setmealDishList);
    }

}
